<script setup>
import { BaseEdge, EdgeLabelRenderer, MarkerType, Position, getBezierPath, useEdge, useNodesData, useVueFlow } from '@vue-flow/core';
import { TransitionPresets, executeTransition, useDebounceFn } from '@vueuse/core';
import { computed, defineEmits, nextTick, ref, toRef, watch } from 'vue';
import Icon from '../icon/Icon.vue';

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  source: {
    type: String,
    required: true,
  },
  target: {
    type: String,
    required: true,
  },
  sourceX: {
    type: Number,
    required: true,
  },
  sourceY: {
    type: Number,
    required: true,
  },
  targetX: {
    type: Number,
    required: true,
  },
  targetY: {
    type: Number,
    required: true,
  },
  sourcePosition: {
    type: String,
    default: Position.Right,
  },
  targetPosition: {
    type: String,
    default: Position.Left,
  },
  data: {
    type: Object,
    required: false,
  },
  markerEnd: {
    type: String,
    required: false,
  },
  style: {
    type: Object,
    required: false,
  },
  showToolbar: {
    type: Boolean,
    required: false,
  }
})

function uuid() {
  return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

const emits = defineEmits(['edgeControlsOpen','edgeControlsClose','layoutGraph']);

const curve = ref()

const dot = ref()

const transform = ref({ x: 0, y: 0 })

const showDot = ref(false)

const { onNodeDoubleClick, fitBounds, fitView, removeEdges, onEdgeClick, findEdge, addNodes, addEdges } = useVueFlow()
const { edge } = useEdge()

// const edge = findEdge(props.id)



const nodesData = useNodesData([props.target, props.source])

const edgePoint = ref(0)

const edgeRef = ref()

const labelPosition = ref({ x: 0, y: 0 })

const currentLength = ref(0)

const targetNodeData = toRef(() => nodesData.value[0].data)

const sourceNodeData = toRef(() => nodesData.value[1].data)

const isFinished = toRef(() => sourceNodeData.value.isFinished)

const isCancelled = toRef(() => targetNodeData.value.isCancelled)

const isAnimating = ref(false)

const edgeColor = toRef(() => {
  if (targetNodeData.value.hasError) {
    return '#f87171'
  }

  if (targetNodeData.value.isFinished) {
    return '#42B983'
  }

  if (targetNodeData.value.isCancelled || targetNodeData.value.isSkipped) {
    return '#fbbf24'
  }

  if (targetNodeData.value.isRunning || isAnimating.value) {
    return '#2563eb'
  }

  return '#6b7280'
})

// const path = computed(() => getSmoothStepPath(props))

const path = computed(() =>
  getBezierPath({
    sourceX: props.sourceX,
    sourceY: props.sourceY,
    sourcePosition: props.sourcePosition,
    targetX: props.targetX,
    targetY: props.targetY,
    targetPosition: props.targetPosition,
  }),
)

watch(isCancelled, (isCancelled) => {
  if (isCancelled) {
    reset()
  }
})

watch(isAnimating, (isAnimating) => {
  const edge = findEdge(props.id)

  if (edge) {
    // we set the `isAnimating` flag, so we can wait until the next node gets executed
    edge.data = {
      ...edge.data,
      isAnimating,
    }
  }
})

watch(edgePoint, (point) => {
  const pathEl = edgeRef.value?.pathEl

  if (!pathEl || point === 0 || !isAnimating.value) {
    return
  }

  const nextLength = pathEl.getTotalLength()

  // if length changed, restart animation
  if (currentLength.value !== nextLength) {
    runAnimation()
    return
  }

  labelPosition.value = pathEl.getPointAtLength(point)
})

watch(isFinished, (isFinished) => {
  if (isFinished) {
    runAnimation()
  }
})

async function runAnimation() {
  const pathEl = edgeRef.value?.pathEl

  if (!pathEl) {
    return
  }

  const totalLength = pathEl.getTotalLength()

  // if animation restarted, use last edgePoint value to continue from
  const from = edgePoint.value || 0

  // update initial label position
  labelPosition.value = pathEl.getPointAtLength(from)

  isAnimating.value = true

  // update currentLength value, so we can check if the path length changed during animation
  if (currentLength.value !== totalLength) {
    currentLength.value = totalLength
  }

  await executeTransition(edgePoint, from, totalLength, {
    transition: TransitionPresets.easeInOutCubic,
    duration: Math.max(1500, totalLength / 2),
    abort: () => !isAnimating.value,
  })

  reset()
}

function reset() {
  nextTick(() => {
    edgePoint.value = 0
    currentLength.value = 0
    labelPosition.value = { x: 0, y: 0 }
    isAnimating.value = false
  })
}



const debouncedFitBounds = useDebounceFn(fitBounds, 1, { maxWait: 1 })

onNodeDoubleClick(({ node }) => {
  // const isSource = props.source === node.id
  // const isTarget = props.target === node.id

  // if (!showDot.value && (isSource || isTarget)) {
  //   showDot.value = true
  //   let totalLength = curve.value.getTotalLength()
  //   const initialPos = ref(isSource ? 0 : totalLength)
  //   let stopHandle

  //   const output = useTransition(initialPos, {
  //     duration: Math.floor(totalLength / 2 / 100) * 1000,
  //     transition: TransitionPresets.easeOutCubic,
  //     onFinished: () => {
  //       stopHandle?.()
  //       showDot.value = false
  //       fitView({
  //         nodes: [isSource ? props.target : props.source],
  //         duration: 500,
  //       })
  //     },
  //   })

  //   transform.value = curve.value.getPointAtLength(output.value)

  //   debouncedFitBounds(
  //     {
  //       width: 100,
  //       height: 200,
  //       x: transform.value.x - 100,
  //       y: transform.value.y - 100,
  //     },
  //     { duration: 500 },
  //   )

  //   setTimeout(() => {
  //     initialPos.value = isSource ? totalLength : 0

  //     stopHandle = watchDebounced(
  //       output,
  //       (next) => {
  //         if (!showDot.value) {
  //           return
  //         }

  //         const nextLength = curve.value.getTotalLength()

  //         if (totalLength !== nextLength) {
  //           totalLength = nextLength
  //           initialPos.value = isSource ? totalLength : 0
  //         }

  //         transform.value = curve.value.getPointAtLength(next)

  //         debouncedFitBounds({
  //           width: 100,
  //           height: 200,
  //           x: transform.value.x - 100,
  //           y: transform.value.y - 100,
  //         })
  //       },
  //       { debounce: 1 },
  //     )
  //   }, 500)
  // }
})

const labelShow = ref(false)
// 点击连线
onEdgeClick((event, edge) => {
  // labelShow.value = true
  // edgeActive.value = true
  // currEdge.value = event.edge
  // console.log(event.edge)
})

const edgeControlsOpenClick = () => {
  emits('edgeControlsClose', {})
  edge.selected = true
  emits('edgeControlsOpen', edge)
}

onMounted(() => {
  watch(() => edge.showToolbar, (newVal, oldVal) => {
    labelShow.value = newVal
  }, { immediate: true, deep: true }); 

});

const removeEdgeClick = () => {
  removeEdges([edge.id])
}

const addNodeClick = () => {
  const sourceNode = edge.sourceNode;
  const targetNode = edge.targetNode;

  const nodeData = JSON.parse(JSON.stringify(sourceNode));
  const uid = uuid();
  nodeData.data.id = uid;

  const newNode = {
    id: uid,
    type: nodeData.type,
    position: {
      x: nodeData.position.x + 250,
      y: nodeData.position.y
    },
    label: nodeData.label,
    data: nodeData.data
  }
  addNodes([newNode])

  addEdges([{
    source: sourceNode.id,
    target: newNode.id,
    sourceHandle: null,
    targetHandle: null,
    animated: true,
    id: uuid(),
    type: 'animation',
    label: '',
    updatable: true,
    showToolbar: false,
    markerEnd: MarkerType.ArrowClosed,
    data: {type: 'default'}
  }])

  addEdges([{
    source: newNode.id,
    target: targetNode.id,
    sourceHandle: null,
    targetHandle: null,
    animated: true,
    id: uuid(),
    type: 'animation',
    label: '',
    updatable: true,
    showToolbar: false,
    markerEnd: MarkerType.ArrowClosed,
    data: {type: 'default'}
  }])
  emits('edgeControlsClose', {})
  removeEdges([edge.id])
  emit('layoutGraph', 'LR')
}
</script>

<script>
export default {
  name: 'AnimationEdge',
  inheritAttrs: false,
}
</script>

<template>
  <path :id="id" ref="curve" :style="style" class="vue-flow__edge-path" :d="path[0]" :marker-end="markerEnd" />

  <Transition name="fade">
    <circle
      v-if="showDot"
      ref="dot"
      r="5"
      cy="0"
      cx="0"
      :transform="`translate(${transform.x}, ${transform.y})`"
      style="fill: #fdd023"
    />
  </Transition>

  <BaseEdge :id="id" ref="edgeRef" :path="path[0]" :style="[style, { stroke: edgeColor }]" :marker-end="markerEnd"/>

  <EdgeLabelRenderer v-if="isAnimating">
    <div
      @click.stop.prevent="edgeControlsOpenClick"
      :style="{ transform: `translate(-50%, -50%) translate(${labelPosition.x}px,${labelPosition.y}px)` }"
      class="nodrag nopan animated-edge-label"
    >
      <span class="truck">
        <Icon class="truck" name="pointFilled"></Icon>
      </span>
    </div>
  </EdgeLabelRenderer>

  <EdgeLabelRenderer v-if="edge.label || labelShow">
    <div
      @click.stop.prevent="edgeControlsOpenClick"
      :style="{
        pointerEvents: 'all',
        position: 'absolute',
        transform: `translate(-50%, -50%) translate(${path[1]}px,${path[2]}px)`,
      }"
      class="nodrag nopan edge-line-label"
    >
      <div 
        v-if="edge.showToolbar"
        style="
        position: absolute;
        inline-size: 40px; 
        inset-block-start: -15px; 
        inset-inline-start: 50%; 
        transform: translate(-50%, -50%)"
      >
        <span>
          <vs-tooltip placement="top">
            <vs-button color="#195bff" shape="circle" icon type="floating" @click="addNodeClick" style="float: inline-start;">
              <vs-icon v-if="false" size="30">
                <vs-icon-plus />
              </vs-icon>
            </vs-button>
            <template #content> 插入节点 </template>
          </vs-tooltip>
          <vs-tooltip placement="top">
            <vs-button color="#ff3e4e" shape="circle" icon type="floating" @click="removeEdgeClick" style="float: inline-start;margin-inline-start: 8px;">
              <vs-icon v-if="false" size="30">
                <vs-icon-plus />
              </vs-icon>
            </vs-button>
            <template #content> 删除路径 </template>
          </vs-tooltip>
        </span>
      </div>
      <span v-if="edge.label" style="padding: 5px;border-radius: 5px;background-color: #fff;">{{ edge.label }}</span>
      <span v-if="edge.data.id" style="padding: 5px;border-radius: 5px;background-color: #fff;">id:{{ edge.data.id }}</span>
      <span v-if="edge.data.tag" style="padding: 5px;border-radius: 5px;background-color: #fff;">tag:{{ edge.data.tag }}</span>
    </div>
  </EdgeLabelRenderer>
</template>

<style>
.animated-edge-label {
  position: absolute;
  z-index: 100;
}

.truck {
  position: relative;
  display: inline-block;
  transform: scaleX(-1);
}

.box {
  position: absolute;
  inset-block-start: -10px;
}

</style>
